package com.shiva.oms.logview.api.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JDialog;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.wb.swt.SWTResourceManager;

import com.sf.shiva.oms.common.util.CollectionUtil;
import com.sf.shiva.oms.common.util.DateUtil;
import com.shiva.oms.logview.api.model.LogFileDirTreeModel;
import com.shiva.oms.logview.api.model.TableColumns;
import com.shiva.oms.logview.domain.ConnectCfg;
import com.shiva.oms.logview.domain.LogData;
import com.shiva.oms.logview.util.SshTransferHelper;
import com.shiva.oms.server.LogViewerParserService;

/**
 * 
 * 描述：
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2018年4月22日         YC           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author YC
 * @version 1.0
 */
public class SwtMainWin {

    protected Shell shell;
    private Text text;
    private Combo patternCombo;
    private Button btnError;
    private Button btnWarn;
    private Button btnInfo;
    private Combo filterCombo;
    private Tree tree;
    private TreeItem root;
    private TableViewer tableViewer;
    private Table table;
    private StyledText styledText;
    private Label fileNameLabel;
    private Label countLabel;

    private LogViewerParserService service;
    private SshTransferHelper sshConn;
    private ConnectCfg connectCfg = new ConnectCfg();
    private List<LogData> list = new ArrayList<>();
    private Map<String, Integer> categoryNames = new HashMap<>();
    private String countLabelStrFormat = "共 %d条";
    private String selectedFileName = "日志文件";
    private int rightClickRowIndex;
    private LogFileDirTreeModel selectedFileNode;


    /**
     * Launch the application.
     * @param args
     */
    public static void main(String[] args) {
        try {
            SwtMainWin window = new SwtMainWin();
            window.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Open the window.
     */
    public void open() {
        Display display = Display.getDefault();
        createContents();
        shell.open();
        shell.layout();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    /**
     * Create contents of the window.
     */
    protected void createContents() {
        shell = new Shell();
        shell.setSize(1111, 780);
        shell.setText("SWT Application");
        shell.setLayout(new FormLayout());

        createMenu(); // 菜单栏

        Composite composite = new Composite(shell, SWT.NONE);
        FormData fd_composite = new FormData();
        fd_composite.top = new FormAttachment(0, 10);
        fd_composite.left = new FormAttachment(0, 10);
        fd_composite.bottom = new FormAttachment(0, 685);
        fd_composite.right = new FormAttachment(0, 1085);
        composite.setLayoutData(fd_composite);

        createCdBar(composite);// 解析文件配置和过滤条件

        ScrolledComposite scrolledComposite = new ScrolledComposite(composite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
        scrolledComposite.setBounds(10, 50, 160, 333);
        scrolledComposite.setExpandHorizontal(true);
        scrolledComposite.setExpandVertical(true);

        tree = new Tree(scrolledComposite, SWT.BORDER);
        tree.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
        tree.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) { // 单击

            }

            @Override
            public void widgetDefaultSelected(SelectionEvent e) { // 双击
                TreeItem item = (TreeItem) e.item;
                if (item == null || item.getData() == null) { // 只处理叶子节点
                    return;
                }
                selectedFileNode = (LogFileDirTreeModel) item.getData();
                System.out.println("开始解析：" + selectedFileNode.getNodeName());
                try {
                    String patternName = (String) patternCombo.getText();
                    fillLogData(patternName, new FileInputStream(selectedFileNode.getFile()));
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
        });
        
        root = new TreeItem(tree, SWT.NONE);
        root.setText("Dir");
        
//        filePopupmenu = new Menu(tree);
//        MenuItem loadItem = new MenuItem(filePopupmenu, SWT.PUSH);
//        loadItem.addSelectionListener(new SelectionAdapter() {
//
//            @Override
//            public void widgetSelected(SelectionEvent e) {
//                System.out.println(e);
//            }
//        });
//        loadItem.setText("解析文件");
//        loadItem.addMouseListener(new MouseAdapter() {
//
//            @Override
//            public void mousePressed(MouseEvent e) {
//                if (selectedFileNode != null) {
//                    System.out.println("开始解析：" + selectedFileNode.getNodeName());
//                    try {
//                        String patternName = (String) patternCombo.getText();
//                        fillLogData(patternName, new FileInputStream(selectedFileNode.getFile()));
//                    } catch (FileNotFoundException e1) {
//                        e1.printStackTrace();
//                    }
//                }
//            }
//        });
//        MenuItem delNodeItem = new MenuItem(filePopupmenu, SWT.PUSH);
//        delNodeItem.setText("删除");
//        delNodeItem.addMouseListener(new MouseAdapter() {
//
//            @Override
//            public void mousePressed(MouseEvent e) {
////                if (selectedFileNode != null) {
////                    System.out.println("delete：" + selectedFileNode.getNodeName());
////                    TreePath currentSelection = tree.getSelectionPath();
////                    if (currentSelection != null) {
////                        DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) (currentSelection
////                                .getLastPathComponent());
////                        MutableTreeNode parent = (MutableTreeNode) (currentNode.getParent());
////                        if (parent != null) {
////                            DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
////                            model.removeNodeFromParent(currentNode);
////                            panel.repaint();
////                            return;
////                        }
////                    } // Either there was no selection, or the root was
////                      // selected.
////                      // toolkit.beep();
////                }
//            }
//        });
//        tree.setMenu(filePopupmenu);
        
        scrolledComposite.setContent(tree);
        scrolledComposite.setMinSize(tree.computeSize(SWT.DEFAULT, SWT.DEFAULT));

        ScrolledComposite scrolledComposite_1 = new ScrolledComposite(composite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
        scrolledComposite_1.setBounds(173, 50, 902, 333);
        scrolledComposite_1.setExpandHorizontal(true);
        scrolledComposite_1.setExpandVertical(true);

        tableViewer = new TableViewer(scrolledComposite_1, SWT.BORDER | SWT.FULL_SELECTION);
        table = tableViewer.getTable();
        table.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                TableItem item = table.getSelection()[0];
                if (item != null) {
                    fillLogDetailText(item);
                }
            }
        });
        table.setLinesVisible(true);
        table.setHeaderVisible(true);
        scrolledComposite_1.setContent(table);
        scrolledComposite_1.setMinSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT));

        ScrolledComposite scrolledComposite_2 = new ScrolledComposite(composite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
        scrolledComposite_2.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
        scrolledComposite_2.setBounds(10, 388, 1065, 277);
        scrolledComposite_2.setExpandHorizontal(true);
        scrolledComposite_2.setExpandVertical(true);

        styledText = new StyledText(scrolledComposite_2, SWT.BORDER);
        styledText.setBackground(SWTResourceManager.getColor(SWT.COLOR_INFO_BACKGROUND));
        scrolledComposite_2.setContent(styledText);
        scrolledComposite_2.setMinSize(styledText.computeSize(SWT.DEFAULT, SWT.DEFAULT));

        countLabel = new Label(shell, SWT.NONE);
        FormData fd_countLabel = new FormData();
        fd_countLabel.top = new FormAttachment(composite, 10);
        fd_countLabel.right = new FormAttachment(100, -29);
        fd_countLabel.left = new FormAttachment(100, -165);
        countLabel.setLayoutData(fd_countLabel);

        fileNameLabel = new Label(shell, SWT.NONE);
        FormData fd_fileNameLabel = new FormData();
        fd_fileNameLabel.left = new FormAttachment(countLabel, -433, SWT.LEFT);
        fd_fileNameLabel.top = new FormAttachment(composite, 10);
        fd_fileNameLabel.right = new FormAttachment(countLabel, -351);
        fileNameLabel.setLayoutData(fd_fileNameLabel);
        fileNameLabel.setText("日志文件");

        ProgressBar progressBar = new ProgressBar(shell, SWT.NONE);
        progressBar.setEnabled(false);
        FormData fd_progressBar = new FormData();
        fd_progressBar.bottom = new FormAttachment(countLabel, 0, SWT.BOTTOM);
        fd_progressBar.left = new FormAttachment(fileNameLabel, 16);
        progressBar.setLayoutData(fd_progressBar);

    }

    protected void createCdBar(Composite composite) {
        Label label = new Label(composite, SWT.NONE);
        label.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
        label.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.BOLD));
        label.setBounds(10, 13, 61, 17);
        label.setText("日志模板");

        patternCombo = new Combo(composite, SWT.NONE);
        patternCombo.setItems(new String[] { "sgsMicro", "novatar" });
        patternCombo.setBounds(77, 10, 118, 25);
        patternCombo.select(0);

        Label label_1 = new Label(composite, SWT.NONE);
        label_1.setText("日志级别");
        label_1.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.BOLD));
        label_1.setBounds(221, 13, 61, 17);

        btnError = new Button(composite, SWT.CHECK);
        btnError.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                System.out.println("errBtn:");
                if (table != null && list != null) {
                    filterByLevel(list);
                }
            }
        });
        btnError.setSelection(true);
        btnError.setBounds(288, 13, 61, 17);
        btnError.setText("Error");

        btnWarn = new Button(composite, SWT.CHECK);
        btnWarn.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                if (table != null && list != null) {
                    filterByLevel(list);
                }
            }
        });
        btnWarn.setSelection(true);
        btnWarn.setText("Warn");
        btnWarn.setBounds(355, 13, 61, 17);

        btnInfo = new Button(composite, SWT.CHECK);
        btnInfo.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                if (table != null && list != null) {
                    filterByLevel(list);
                }
            }
        });
        btnInfo.setSelection(true);
        btnInfo.setText("Info");
        btnInfo.setBounds(439, 13, 61, 17);

        Label label_2 = new Label(composite, SWT.NONE);
        label_2.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.BOLD));
        label_2.setBounds(551, 15, 61, 17);
        label_2.setText("筛选条件");

        filterCombo = new Combo(composite, SWT.NONE);
        filterCombo.setItems(new String[] { "关键字", "时间早于", "时间晚于" });
        filterCombo.setBounds(618, 12, 118, 25);
        filterCombo.select(0);

        text = new Text(composite, SWT.BORDER);
        text.setBounds(740, 12, 170, 23);

        Button button = new Button(composite, SWT.NONE);
        button.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                switch(filterCombo.getSelectionIndex()){
                    case 0:
                        return ;//filterByKeyword(getTableDatas(), textField_2.getText());
                    case 1:
                        return;
                    case 2:
                        return;
                    default:
                        return;
                }
            }
        });
        button.setBounds(926, 10, 70, 27);
        button.setText("筛选");

        Button button_1 = new Button(composite, SWT.NONE);
        button_1.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                fresh(list);
            }
        });
        button_1.setText("刷新");
        button_1.setBounds(1005, 10, 70, 27);
    }

    protected void createMenu() {
        Menu menu = new Menu(shell, SWT.BAR);
        shell.setMenuBar(menu);

        MenuItem mntmNewSubmenu = new MenuItem(menu, SWT.CASCADE);
        mntmNewSubmenu.setText("文件");

        Menu menu_1 = new Menu(mntmNewSubmenu);
        mntmNewSubmenu.setMenu(menu_1);

        MenuItem menuItem = new MenuItem(menu_1, SWT.NONE);
        menuItem.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                File file = getFileByDialog();
                if (file == null) {
                    return;
                }
                if (file.isFile()) {
                    // System.out.println("文件:" + file.getAbsolutePath());
                    selectedFileName = file.getName();
                    TreeItem node = new TreeItem(root, SWT.NONE);
                    root.setExpanded(true);
                    node.setData(new LogFileDirTreeModel(file));
                    node.setText(selectedFileName);
                }
            }
        });
        menuItem.setText("打开文件");

        MenuItem mntmNewItem = new MenuItem(menu_1, SWT.NONE);
        mntmNewItem.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                File files = getDirByDialog();
                System.out.println("文件夹:" + files.getAbsolutePath());
                TreeItem dirNode = new TreeItem(root, SWT.NONE);
                dirNode.setData(new LogFileDirTreeModel(files));
                dirNode.setText(files.getName());
                root.setExpanded(true);
                File[] tempList = files.listFiles();
                for (int i = 0; i < tempList.length; i++) {
                    if (tempList[i].isFile()) {
                        TreeItem node = new TreeItem(dirNode, SWT.NONE);
                        node.setData(new LogFileDirTreeModel(tempList[i]));
                        node.setText(tempList[i].getName());
                    }
                }
                dirNode.setExpanded(true);
            }
        });
        mntmNewItem.setText("打开文件夹");

        MenuItem menuItem_3 = new MenuItem(menu_1, SWT.NONE);
        menuItem_3.setText("最近打开");

        new MenuItem(menu_1, SWT.SEPARATOR);

        MenuItem menuItem_4 = new MenuItem(menu_1, SWT.NONE);
        menuItem_4.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                NewConnectCfgGui dialog = new NewConnectCfgGui(connectCfg);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
                connectAndGetLog(connectCfg);
            }
        });
        menuItem_4.setText("新建连接");

        MenuItem menuItem_5 = new MenuItem(menu_1, SWT.NONE);
        menuItem_5.setText("最近连接");

        new MenuItem(menu_1, SWT.SEPARATOR);

        MenuItem menuItem_2 = new MenuItem(menu_1, SWT.NONE);
        menuItem_2.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                saveFileByDialog();
            }
        });
        menuItem_2.setText("保存文件");

        MenuItem menuItem_1 = new MenuItem(menu_1, SWT.NONE);
        menuItem_1.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.dispose();
            }
        });
        menuItem_1.setText("退出");

        MenuItem menuItem_6 = new MenuItem(menu, SWT.CASCADE);
        menuItem_6.setText("编辑");

        Menu menu_2 = new Menu(menuItem_6);
        menuItem_6.setMenu(menu_2);

        MenuItem menuItem_7 = new MenuItem(menu, SWT.CASCADE);
        menuItem_7.setText("工具");

        Menu menu_3 = new Menu(menuItem_7);
        menuItem_7.setMenu(menu_3);

        MenuItem menuItem_10 = new MenuItem(menu_3, SWT.NONE);
        menuItem_10.setText("日志模板配置");

        MenuItem menuItem_11 = new MenuItem(menu_3, SWT.NONE);
        menuItem_11.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                ConnectCfgGui dialog = new ConnectCfgGui(connectCfg);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
                connectAndGetLog(connectCfg);
            }
        });
        menuItem_11.setText("连接配置管理");

        MenuItem menuItem_8 = new MenuItem(menu, SWT.CASCADE);
        menuItem_8.setText("帮助");

        Menu menu_4 = new Menu(menuItem_8);
        menuItem_8.setMenu(menu_4);

        MenuItem menuItem_9 = new MenuItem(menu_4, SWT.NONE);
        menuItem_9.setText("关于");
    }
    
    private void createTableHeader(TableColumns[] headNames) {
        TableColumn[] cols = table.getColumns();
        for (int i = 0; i < cols.length; i++) {
            cols[i].dispose();
        }
        for (int i = 0; i < headNames.length; i++) {
            TableColumn column = new TableColumn(table, SWT.NULL);
            column.setText(headNames[i].getHeadName());
            column.pack();
            switch (headNames[i].getColumn()) {
                case 0:
                    column.setWidth(50);
                    break;
                case 1:
                    column.setWidth(100);
                    break;
                case 2:
                    column.setWidth(50);
                    break;
                case 3:
                    column.setWidth(300);
                    break;
                case 4:
                    column.setWidth(150);
                    break;
                case 5:
                    column.setWidth(300);
                    break;
                default:
                    column.setWidth(100);
            }
        }

    }
    private void load(List<LogData> list, TableColumns[] headNames) {
        // table.clearAll();
        createTableHeader(headNames);
        // tableViewer.setInput(list);
        for (int i = 0; i < list.size(); i++) {
            LogData data = list.get(i);
            TableItem item = new TableItem(table, SWT.NONE);
            item.setText(new String[] {
                    i + "",
                    DateUtil.date2String(data.getDate()),
                    data.getLevel().toString(),
                    data.getClazz(),
                    data.getMethod(),
                    data.getMessage().substring(0,data.getMessage().length() > 100 ? 100 : data.getMessage().length() - 1) });
            item.setData(data);
        }
        styledText.setText("");
        fileNameLabel.setText(selectedFileName);
        countLabel.setText(String.format(countLabelStrFormat, list.size()));
    }

    /**
     * 解析日志并刷新显示
     * 
     * @param patternName
     * @param input
     * @author LA.01367604-2018年4月18日
     */
    private void fillLogData(String patternName, InputStream input) {
        service = new LogViewerParserService();
        list.clear();
        try {
            list = service.parse(input);
            // categoryNames = service.getCategoryNames();
            load(list, service.getHeadNames());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    private String detailFormat = "    id :%s\n" + "   date :%s\n" + "  level:%s\n" + "  line :%s\n"
            + "   ndc :%s\n" + " thread:%s\n" + " clazz :%s\n" + "method :%s\n" + "message:%s";


    private void fillLogDetailText(TableItem item) {
        LogData data = (LogData) item.getData();
        String content = String.format(detailFormat, data.getId(), DateUtil.date2String(data.getDate()), data.getLevel().toString(), data.getLine(),
            data.getNdc(), data.getThread(), data.getClazz(), data.getMethod(), data.getMessage());
        styledText.setText(content);
    }
    
    /**
     * 刷新数据：表格、底部label显示等
     * 
     * @param showList
     * @author LA.01367604-2018年4月18日
     */
    private void fresh(List<LogData> showList) {
        table.removeAll();
        for (int i = 0; i < showList.size(); i++) {
            LogData data = showList.get(i);
            TableItem item = new TableItem(table, SWT.NONE);
            item.setText(new String[] {
                    i + "",
                    DateUtil.date2String(data.getDate()),
                    data.getLevel().toString(),
                    data.getClazz(),
                    data.getMethod(),
                    data.getMessage().substring(0,data.getMessage().length() > 100 ? 100 : data.getMessage().length() - 1) });
            item.setData(data);
        }
        styledText.setText("");
        fileNameLabel.setText(selectedFileName);
        countLabel.setText(String.format(countLabelStrFormat, showList.size()));
    }
    
    /**
     * 根据日志级别过滤（checkbox）
     * 
     * @author LA.01367604-2018年4月18日
     */
    private void filterByLevel(List<LogData> list) {
        if (CollectionUtil.isEmpty(list) || btnError == null || btnWarn == null || btnInfo == null) {
            return;
        }
        List<String> selectedLevel = new ArrayList<>();
        if (btnError.getSelection()) {
            selectedLevel.add("ERROR");
        }
        if (btnWarn.getSelection()) {
            selectedLevel.add("WARN");
        }
        if (btnInfo.getSelection()) {
            selectedLevel.add("INFO");
        }
        List<LogData> showList = service.filterByLevel(list, selectedLevel);
        fresh(showList);
    }

    private void filterByKeyword(List<LogData> list, String keyword) {
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        List<LogData> showList = service.filterByKeyword(list, keyword);
        fresh(showList);
    }

    private File getFileByDialog() {
        FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);
        // 指定打开窗口时的默认路径。可以设置绝对和相对路径，这里设置的是当前文件所在的路径。
        fileDialog.setFilterPath("./");
        // 设置过滤文件的名字，里面参数是一个String数组，过滤的名字可以指定也可以不指定。比如我这里只指定
        // 了2个过滤文件的名字，最后一个exe文件的名字 并没有指定，但是当设置了文件类型后，默认把文件类型.exe作为此过滤文件的名字。
        fileDialog.setFilterNames(new String[] { "所有文件(*.*)" });
        // 设置过滤文件的类型，里面也是String数组。也就是说上面的名字怎么设置都无所谓，而真正过滤文件的是
        // 下面所指定的类型。
        fileDialog.setFilterExtensions(new String[] { "*.*" });
        // 最后需要使用open()方法来打开此对话框。当关闭对话框后会返回一个选择文件的绝对路径。如果点取消
        // 或者直接关闭对话框的话，会返回null。
        String fileName = fileDialog.open();
        // System.out.println(fileName);
        if (StringUtils.isNotBlank(fileName)) {
            return new File(fileName);
        } else {
            return null;
        }
    }

    private File getDirByDialog() {
        // 新建文件夹（目录）对话框
        DirectoryDialog folderdlg = new DirectoryDialog(shell, SWT.OPEN);
        // 设置文件对话框的标题
        folderdlg.setText("文件选择");
        // 设置初始路径 SystemDrive
        folderdlg.setFilterPath("./");
        // 设置对话框提示文本信息
        folderdlg.setMessage("请选择相应的文件夹");
        // 打开文件对话框，返回选中文件夹目录
        String selectedDir = folderdlg.open();
        System.out.println(selectedDir);
        if (StringUtils.isNotBlank(selectedDir)) {
            return new File(selectedDir);
        } else {
            return null;
        }
    }

    private void saveFileByDialog() {
        // 保存文件对话框和打开文件对话框基本上一样，唯一不同的就是FileDialog构造器中第2个参数改为SWT.SAVE就表示该对话框是保存文件的对话框。
        FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);
        fileDialog.setFilterPath("./");
        fileDialog.setFilterNames(new String[] { "所有文件(*.*)" });
        fileDialog.setFilterExtensions(new String[] { "*.*" });
        String fileName = fileDialog.open();
        System.out.println(fileName);
    }
    
    private void connectAndGetLog(ConnectCfg connectCfg) {
        if (StringUtils.isNotBlank(connectCfg.getIp()) && StringUtils.isNotBlank(connectCfg.getUser()) && StringUtils.isNotBlank(connectCfg.getPassword())){
            sshConn = new SshTransferHelper(connectCfg.getIp(), connectCfg.getUser(), connectCfg.getPassword());
            String fileName = "novatar_20180412.0.log";
            String patternName = "novatar";
            InputStream is = sshConn.getFileContent(connectCfg.getFileDir() + fileName);
            selectedFileName = connectCfg.getFileDir().substring(0,connectCfg.getFileDir().lastIndexOf("/"));
            fillLogData(patternName, is);
        }
    }

    class KeywordTableViewerFilter extends ViewerFilter {

        private String keyword; // 过滤字符串

        public KeywordTableViewerFilter(String keyword) {
            this.keyword= keyword;
        }

        @Override
        public boolean select(Viewer viewer, Object parentElement, Object element) {
            if (StringUtils.isNotBlank(keyword)) {
//                if (element != null && element instanceof TableBean)
//                    if (!((TableBean) element).getTableName().toLowerCase()
//                            .contains(pattern.toLowerCase()))
//                        return false;
            }
            return true;
        }

        public String getKeyword() {
            return keyword;
        }

        public void setKeyword(String keyword) {
            this.keyword = keyword;
        }

    }
}
